package LeetCode.exercise;

import java.util.*;

public class LC49 {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for(String str : strs){
            String tmp = change(str);
            if(!map.containsKey(tmp)){
                if(map.get(tmp) == null){
                    List<String> list = new ArrayList<>();
                    list.add(str);
                    map.put(tmp, list);
                } else {
                    map.get(tmp).add(str);
                    map.put(tmp, map.get(str));
                }
            } else {
                map.get(tmp).add(str);
                map.put(tmp, map.get(tmp));
            }
        }
        List<List<String>> lists = new ArrayList<>(map.values());
        return lists;
    }

    public String change(String str){
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }

    public static void main(String[] args) {
        LC49 l = new LC49();
        System.out.println(l.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
    }
}
